//
//  OAuthViewController.swift
//  sinaweibo
//
//  Created by icefs2 on 15/11/11.
//  Copyright © 2015年 icefs2. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {
    //定义一个webview的属性
    
    let webview = UIWebView()
    let appkey = "3009439533"
    let redirect_uri = "http://www.itcast.cn"
    let appsecret = "ab8b70f924f81b1442f48c9e1e528491"
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func fullAccout() {
        let jsstring = "document.getElementById('userId').value = '13651501381' , document.getElementById('passwd').value = 'Aa213213';"
        webview.stringByEvaluatingJavaScriptFromString(jsstring)
    }

    override func loadView() {
        view = webview
        webview.delegate = self
        
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        laodoauthweb()
    }
    
    private func setupUI() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccout")
    }
    private func laodoauthweb() {
        let urlstr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + appkey + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlstr)
      let requset = NSURLRequest(URL: url!)
        webview.loadRequest(requset)
        
    }
    
    

}
extension OAuthViewController: UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlstring = request.URL?.absoluteString else {
            return false
        }
        
        if urlstring.hasPrefix("https://api.weibo.com") {
            return true
        }
        if !urlstring.hasPrefix(redirect_uri) {
            return false
        }
        //走到这里必定包含code
        print(urlstring)
        
        guard let query = request.URL?.query else {
            return false
        }
        print(query)
         let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        print(code)
        
        loadToken(code)
        return false
    }
    //获取token
    private func loadToken(code: String) {
        let urlstr = "https://api.weibo.com/oauth2/access_token"
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        let parameters = ["client_id" : appkey, "client_secret" : appsecret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" :redirect_uri]
        AFN.POST(urlstr, parameters: parameters, success: { (_, result) -> Void in
            print(result)
            if let dict = result as? [String : AnyObject] {
            let account = UserAccout(dict: dict)
            self.loadUserInfor(account)
                }
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    //开始加载用户数据
    private func loadUserInfor(account: UserAccout) {
        let urlstring = "https://api.weibo.com/2/users/show.json"
        let AFN = AFHTTPSessionManager()
        let parameters = ["access_token" : account.access_token!, "uid" : account.uid!]
        AFN.GET(urlstring, parameters: parameters, success: { (_, result) -> Void in
            if let dict = result as? [String : AnyObject] {
                account.avatar_large = dict["avatar_large"] as? String
                account.name = dict["name"] as? String
                print(account)
            }
            
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
